# -*- coding: utf-8 -*-
"""
cesc wallet bot Project

This project was developed by Seye (cescwalletbot@protonmail.com)

Dependencies:
pip pytelegrambotapi
pip pypng
pip pyqrcode
pip certifi
pip urllib3

"""
#Import section
import cwallet
import clogging
import creply
import cauxiliary
import telebot
import time
import os
import pyqrcode
import random
import json
import requests

version = '0.3.2'

#Create Initial folder structure
if os.path.exists('./log') is False:
    cauxiliary.folder_structure()


#Initial Variables
global time1, fulltext, allowed_users
time1 = time.time()

if os.path.exists('price.json') is False:
    price = {'eur': 0, 'usd': 0}
    json.dump(price, open('price.json', 'w'))

#Language for Server Selection
if os.path.exists('config.json') is False:
    lang_opt = input('Please select a language for your server:\n[1] English\n[2] Português\n')
    while lang_opt not in ('1', '2'):
        lang_opt = input('Please select a valid language:\n[1] English\n[2] Português\n')
    if lang_opt == '1':
        lang = 'en'
        config = {'lang': 'en'}
        json.dump(config, open('config.json', 'w'))
    if lang_opt == '2':
        lang = 'pt'
        config = {'lang': 'pt'}
        json.dump(config, open('config.json', 'w'))
else:
    lang = json.load(open('config.json', 'r'))['lang']

fulltext = json.load(open('./translations/'+ lang +'.json', 'r'))
print(fulltext['server_welcome_1'] + version)

#check if there is a allowed users file
if os.path.exists('allowed_users.cwb') is False:
    cauxiliary.allowed_users(fulltext)
else:
    allowed_users_file = open('allowed_users.cwb','r')
    allowed_users = allowed_users_file.read()
    allowed_users_file.close()

#check if there is a key file, and ask for a key if not
if os.path.exists('key.cwb') is True:
    keyfile = open('key.cwb', 'r')
    key = keyfile.read()
    keyfile.close()
    print(fulltext['server_welcome_2'])
    print(fulltext['server_welcome_3'])
else:
    key = input(fulltext['server_welcome_4'])
    keyfile = open('key.cwb', 'w')
    keyfile.write(key)
    keyfile.close()


#Start the bot
bot = telebot.TeleBot(key)


#All bot handlers
@bot.message_handler(commands=['start'])
def welcome_message(message):
    """Handles commands that start with /start .
    
    Replies to /start commands with some initial information and available commands.
    """
    global allowed_users
    username = message.from_user.username
    if username in allowwed_users:
        reply = json.load(open('./translations/en.json','r'))['start_reply']
        mtext = message.text
        pref_file = './log/userpref/' + str(username) + '.json'
        if os.path.exists(pref_file) is False:
            pref = {'lang': 'en', 'fiat': 'eur'}
            json.dump(pref, open(pref_file, 'w'))
        clogging.userlog(username, mttext, 'Welcome message.')
        bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="new")
@bot.message_handler(regexp="novo")
@bot.message_handler(regexp="New")
@bot.message_handler(regexp="Novo")
@bot.message_handler(commands=['new', 'novo', 'New', 'Novo'])
def new_account(message):
    """Handles commands that start with /new .
    
    Replies to /new commands, by creating a new wallet account, with the account address.
    """
    global allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        language = json.load(open('./log/userpref/' + str(username) + '.json'))['lang']
        address = cwallet.new(username)
        if address == 10:
            if language == 'en':
                reply = json.load(open('./translations/en.json','r'))['new_reply_1']
            if language == 'pt':
                reply = json.load(open('./translations/pt.json','r'))['new_reply_1']
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)
        if address != 10:
            address = str(address)
            address = address[2:36]
            if language == 'en':
                reply = json.load(open('./translations/en.json','r'))['new_reply_2'] + address
            if language == 'pt':
                reply = json.load(open('./translations/pt.json','r'))['new_reply_2'] + address
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="send")
@bot.message_handler(regexp="enviar")
@bot.message_handler(regexp="Send")
@bot.message_handler(regexp="Enviar")
@bot.message_handler(commands=['send', 'enviar', 'Send', 'Enviar'])
def send(message):
    """Handles commands that start with /send .
    
    Replies to /send commands, by sending a coin amount to a specified address.
    """
    global allowed_users
    username = message.from_user.username
    message_text = message.text.split()
    mtext = message.text
    if  username in allowed_users:
        if len(message_text) == 3:
            toaddress = message_text[1]
            amount = message_text[2]
            [txid, sent_amount, fee_amount] = cwallet.send(username, toaddress, amount)
            reply = creply.send_reply(txid, username, sent_amount, fee_amount)
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)
        else:
            language = json.load(open('./log/userpref/' + str(username) + '.json'))['lang']
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['send_reply_12']
            if language == 'pt':
                reply = json.load(open('./translations/pt.json', 'r'))['send_reply_12']
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="balance")
@bot.message_handler(regexp="Balance")
@bot.message_handler(regexp="balanço")
@bot.message_handler(regexp="Balanço")
@bot.message_handler(regexp="balanco")
@bot.message_handler(regexp="Balanco")
@bot.message_handler(commands=['balance', 'balanço', 'balanco', 'Balance', 'Balanço', 'Balanco'])
def balance(message):
    """Handles commands that start with /balance .
    
    Replies to /balance commands, by sending acount balance in altcoin and fiat.
    """
    global time1, time2, allowed_users, fulltext
    username = message.from_user.username
    mtext = message.text
    if username in allowed_users:
        #Asks cryptonator for a conversion price
        time2 = time.time()
        if time2 - time1 > 900:
            try:
                cauxiliary.cryptonator_request()
                time1 = time.time()
            except:
                print(fulltext['server_balance'])
        #Asks wallet for account Balance
        balance = cwallet.balance(username)
        price = json.load(open('price.json', 'r'))
        preference = json.load(open('./log/userpref/' + str(username) + '.json', 'r'))
        language = preference['lang']
        fiat = preference['fiat']
        if balance == -10:
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['balance_reply_1']
            if language == 'pt':
                reply = 'Ainda não se encontra registado. Use /novo para obter um endereço.'
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)
        if balance != -10:
            balance = str(balance)
            for n in range(len(balance), 0, -1):
                balance_test = balance[2:n]
                if cauxiliary.is_float(balance_test) is True:
                    balance = balance_test
                    break
            balancefiat = round(float(balance) * price[fiat], 3)
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['balance_reply_2'] + balance + ' cesc'
                reply = reply + json.load(open('./translations/en.json', 'r'))['balance_reply_2'] + str(balancefiat) + ' ' + fiat
            if language == 'pt':
                reply = json.load(open('./translations/pt.json', 'r'))['balance_reply_2'] + balance + ' cesc'
                reply = reply + json.load(open('./translations/pt.json', 'r'))['balance_reply_2'] + str(balancefiat) + ' ' + fiat
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="endereco")
@bot.message_handler(regexp="Endereco")
@bot.message_handler(regexp="endereço")
@bot.message_handler(regexp="Endereço")
@bot.message_handler(regexp="address")
@bot.message_handler(regexp="Address")
@bot.message_handler(commands=['address', 'endereço', 'endereco', 'Address', 'Endereço', 'Endereco'])
def address(message):
    """Handles commands that start with /address .
    
    Replies to /address commands, by sending address in text and qrcode form.
    """
    global allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        language = json.load(open('./log/userpref/' + str(username) + '.json'))['lang']
        address = cwallet.address(username)
        if address == 10:
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['address_reply_1']
            if language == 'pt':
                reply = json.load(open('./translations/en.json', 'r'))['address_reply_1']
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)
        if address != 10:
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['address_reply_2'] + address
            if language == 'pt':
                reply = json.load(open('./translations/pt.json', 'r'))['address_reply_2'] + address
            clogging.userlog(username, mtext, reply)
            qrcode = pyqrcode.create(address)
            qrcode.png('./log/userqrcode/' + username + '.png', scale=6)
            photo = open('./log/userqrcode/' + username + '.png', 'rb')
            bot.send_photo(message.chat.id, photo)
            os.remove('./log/userqrcode/' + username + '.png')
            bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="ajuda")
@bot.message_handler(regexp="Ajuda")
@bot.message_handler(regexp="help")
@bot.message_handler(regexp="Help")
@bot.message_handler(commands=['help', 'ajuda','Help','Ajuda'])
def help_message(message):
    global fulltext, allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        language = json.load(open('./log/userpref/' + str(username) + '.json', 'r'))['lang']
        if language == 'en':
            reply = json.load(open('./translations/en.json', 'r'))['help_reply']
        if language == 'pt':
            reply = json.load(open('./translations/pt.json', 'r'))['help_reply']
        clogging.userlog(username, mtext, 'Help Message')
        bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="registo")
@bot.message_handler(regexp="Registo")
@bot.message_handler(regexp="transactions")
@bot.message_handler(regexp="Transactions")
@bot.message_handler(commands=['transactions', 'registo', 'Transactions', 'Registo'])
def transactions(message):
    global allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        language = json.load(open('./log/userpref/' + str(username) + '.json', 'r'))['lang']
        transactions = cwallet.transactions(username)
        if len(transactions) < 10:
            if language == 'en':
                reply = json.load(open('./translations/en.json', 'r'))['transactions_reply_1']
            if language == 'pt':
                reply = json.load(open('./translations/pt.json', 'r'))['transactions_reply_1']
            clogging.userlog(username, mtext, reply)
            bot.send_message(message.chat.id, reply)
        if len(transactions) > 10:
            reply = creply.transactions_reply(transactions, username)
            clogging.userlog(username, mtext, 'Transactions')
            bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="setl")
@bot.message_handler(commands=['setl'])
def setl(message):
    global allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        message_text = message.text.split()
        accepted_lang = {'pt', 'en'}
        if len(message_text) < 2:
            clogging.userlog(username, mtext, 'Insert all needed parameters!')
            bot.send_message(message.chat.id, 'Insert all needed parameters!')
        else:
            if str(message_text[1]) in accepted_lang:
                clogging.lang_pref(message)
                clogging.userlog(username, mtext, 'Preference set')
                bot.send_message(message.chat.id, 'Preference set')
            else:
                reply = 'Set a valid language: pt or en'
                clogging.userlog(username, mtext, reply)
                bot.send_message(message.chat.id, reply)


@bot.message_handler(regexp="setc")
@bot.message_handler(commands=['setc'])
def setc(message):
    global allowed_users
    username = message.from_user.username
    if username in allowed_users:
        mtext = message.text
        message_text = message.text.split()
        accepted_fiat = {'eur', 'usd'}
        if len(message_text) < 2:
            clogging.userlog(username, mtext, 'Insert all needed parameters!')
            bot.send_message(message.chat.id, 'Insert all needed parameters!')
        else:
            if str(message_text[1]) in accepted_fiat:
                clogging.fiat_pref(message)
                clogging.userlog(username, mtext, 'Preference set')
                bot.send_message(message.chat.id, 'Preference set')
            else:
                reply = 'Set a valid currency'
                clogging.userlog(username, mtext, reply)
                bot.send_message(message.chat.id, reply)


@bot.message_handler(content_types=['photo'])
def image_handler(message):
    #file_info = tb.get_file(file_id)
    #file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(API_TOKEN, file_info.file_path))
    bot.send_message(message-chat.id, 'Something will happen in a future version')


#Bot polling
try:
    bot.polling(none_stop=True)
except:
    time.sleep(15)